package com.niit.search.service.impl;

import com.niit.search.entity.SearchHistory;
import com.niit.search.entity.Topic;
import com.niit.search.mapper.SearchHistoryMapper;
import com.niit.search.service.SearchHistoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;

@Service
public class SearchHistoryServiceImpl implements SearchHistoryService {
    @Autowired
    private SearchHistoryMapper searchHistoryMapper;

    @Override
    public void saveHistory(Long userId, String keyword) {
        // 确保关键词不为空
        if (keyword == null || keyword.trim().isEmpty()) {
            return;
        }
        
        // 限制关键词长度不超过512个字符，防止数据截断
        if (keyword.length() > 512) {
            keyword = keyword.substring(0, 512);
        }
        
        // 检查是否已存在相同关键词的搜索记录
        SearchHistory existingHistory = searchHistoryMapper.findByKeyword(keyword);
        if (existingHistory != null) {
            // 如果存在，增加搜索次数
            searchHistoryMapper.incrementSearchCount(keyword);
        } else {
            // 如果不存在，创建新记录
            searchHistoryMapper.insertHistory(userId, keyword);
        }
    }

    @Override
    public List<SearchHistory> getHistory(Long userId) {
        // 如果userId为null，返回空列表
        if (userId == null) {
            return java.util.Collections.emptyList();
        }
        return searchHistoryMapper.getHistoryByUserId(userId);
    }
    
    @Override
    public boolean deleteHistoryById(Long userId, Long id) {
        if (userId == null || id == null) {
            return false;
        }
        return searchHistoryMapper.deleteHistoryById(id, userId) > 0;
    }
    
    @Override
    public boolean deleteHistoryByKeyword(Long userId, String keyword) {
        if (userId == null || keyword == null || keyword.trim().isEmpty()) {
            return false;
        }
        // 限制关键词长度不超过512个字符
        if (keyword.length() > 512) {
            keyword = keyword.substring(0, 512);
        }
        return searchHistoryMapper.deleteHistoryByKeyword(keyword, userId) > 0;
    }
    
    @Override
    public List<Topic> getHotTopics() {
        return searchHistoryMapper.getHotTopics();
    }
}